package com.zlzlib.libui.util;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Point;
import android.os.Build;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.Window;
import android.view.WindowManager;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * Created by zlz on 2019/8/29.
 */
public class ScreenUtil {

    /**
     * 用于获取状态栏的高度。
     *
     * @return 返回状态栏高度的像素值。
     */
    public static int getStatusBarHeight(Context context) {
        int statusBarHeight = 0;
        try {
            Class<?> c = Class.forName("com.android.internal.R$dimen");
            Object o = c.newInstance();
            Field field = c.getField("status_bar_height");
            int x = (Integer) field.get(o);
            statusBarHeight = context.getResources().getDimensionPixelSize(x);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return statusBarHeight;
    }

    /**
     * @return 获取屏幕长宽比
     */
    public static float getScreenRate(Context context) {
        Point P = getScreenMetrics(context);
        float H = P.y;
        float W = P.x;
        return (H / W);
    }


    /**
     * 一定值  不随屏幕转动而变化
     * int width = metric.widthPixels;  // 屏幕宽度（像素）
     * int height = metric.heightPixels;  // 屏幕高度（像素）
     * float density = metric.density;  // 屏幕密度（0.75 / 1.0 / 1.5）
     * int densityDpi = metric.densityDpi;  // 屏幕密度DPI（120 / 160 / 240）
     *
     * @return 获取屏幕宽度和高度，单位为px
     */
    public static Point getScreenMetrics(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        int w_screen = dm.widthPixels;
        int h_screen = dm.heightPixels;
        return new Point(w_screen, h_screen);
    }

    /**
     * 一定值  不随屏幕转动而变化
     * int width = metric.widthPixels;  // 屏幕宽度（像素）
     * int height = metric.heightPixels;  // 屏幕高度（像素）
     * float density = metric.density;  // 屏幕密度（0.75 / 1.0 / 1.5）
     * int densityDpi = metric.densityDpi;  // 屏幕密度DPI（120 / 160 / 240）
     *
     * @return 获取屏幕宽度和高度，单位为dp
     */
    public static Point getScreenMetricsDp(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        int width = dm.widthPixels;         // 屏幕宽度（像素）
        int height = dm.heightPixels;       // 屏幕高度（像素）
        float density = dm.density;         // 屏幕密度（0.75 / 1.0 / 1.5）
//        int densityDpi = dm.densityDpi;     // 屏幕密度dpi（120 / 160 / 240）
        // 屏幕宽度算法:屏幕宽度（像素）/屏幕密度
        int screenWidth = (int) (width / density);  // 屏幕宽度(dp)
        int screenHeight = (int) (height / density);// 屏幕高度(dp)
        return new Point(screenWidth, screenHeight);
    }

    /**
     * 随屏幕转动而变化
     *
     * @return 获取屏幕宽度和高度，单位为px
     */
    public static Point getScreenResolution(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        Point screenResolution = new Point();
        display.getSize(screenResolution);
        return screenResolution;
    }

    /**
     * 是否为竖屏
     */
    public static boolean isPortrait(Context context) {
        Point screenResolution = getScreenResolution(context);
        return screenResolution.y > screenResolution.x;
    }

    /**
     * 状态栏透明只有Android 4.4 以上才支持
     */
    public static boolean setTranslucentStatus(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = activity.getWindow();
            WindowManager.LayoutParams layoutParams = window.getAttributes();
            layoutParams.flags |= WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
            window.setAttributes(layoutParams);
            return true;
        }
        return false;
    }


    /**
     * 全屏只有Android 4.4 以上才支持
     */
    public static boolean setFullScreen(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = activity.getWindow();
            WindowManager.LayoutParams layoutParams = window.getAttributes();
            layoutParams.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
            window.setAttributes(layoutParams);
            return true;
        }
        return false;
    }

    /**
     * 设置当前通知栏文字主题为深色还是浅色
     * 6.0 以上有效
     *
     * @param activity 页面
     * @param dark     true = 深色
     */
    public static boolean setStatusBarColor(Activity activity, boolean dark) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            View decor = activity.getWindow().getDecorView();
            if (dark) {
                decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            } else {
                decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            }
            return true;
        }
        return false;
    }

    //设置状态栏的padding
    public static void setStatusPad(View view, Context context) {
        //大于4.4才能透明通知栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            view.setPadding(0, getStatusBarHeight(context), 0, 0);
        }
    }

    public static void setStatusPad(View view) {
        //大于4.4才能透明通知栏
        setStatusPad(view, view.getContext());
    }


    //获取虚拟按键的高度
    public static int getNavigationBarHeight(Context context) {
        int result = 0;
        if (hasNavBar(context)) {
            Resources res = context.getResources();
            int resourceId = res.getIdentifier("navigation_bar_height", "dimen", "android");
            if (resourceId > 0) {
                result = res.getDimensionPixelSize(resourceId);
            }
        }
        return result;
    }

    /**
     * @return 是否存在虚拟按键栏
     */
    private static boolean hasNavBar(Context context) {
        Resources res = context.getResources();
        int resourceId = res.getIdentifier("config_showNavigationBar", "bool", "android");
        if (resourceId != 0) {
            boolean hasNav = res.getBoolean(resourceId);
            // check override flag
            String sNavBarOverride = getNavBarOverride();
            if ("1".equals(sNavBarOverride)) {
                hasNav = false;
            } else if ("0".equals(sNavBarOverride)) {
                hasNav = true;
            }
            return hasNav;
        } else { // fallback
            return !ViewConfiguration.get(context).hasPermanentMenuKey();
        }
    }

    /**
     * @return 判断虚拟按键栏是否重写
     */
    private static String getNavBarOverride() {
        String sNavBarOverride = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            try {
                Class<?> c = Class.forName("android.os.SystemProperties");
                Method m = c.getDeclaredMethod("get", String.class);
                m.setAccessible(true);
                sNavBarOverride = (String) m.invoke(null, "qemu.hw.mainkeys");
            } catch (Throwable ignored) {
            }
        }
        return sNavBarOverride;
    }

    /**
     * 设置屏幕方向
     * ActivityInfo.SCREEN_ORIENTATION_PORTRAIT  (竖直)
     * ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE  (水平)
     * ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED  (默认值)
     * <p>
     * <p>
     * unspecified - 默认值，由系统选择显示方向
     * landscape   - 橫向
     * portrait    - 纵向
     * reverseLandscape    - 反横向(API >= 9)
     * reversePortrait     - 反纵向(API >= 9)
     * user        - 用户当前的首选方向
     * behind      - 与Activity堆栈下的方向相同
     * sensor      - 根据物理传感器方向3/4个方向(取决于设备)
     * fullSensor  - 根据物理传感器方向4个方向
     * nosensor    - 不按照物理传感器方向，除此之外与"unspecified"无区别
     * sensorLandscape     - 按照物理传感器，只在横向(2个方向)进行翻转(API >= 9)
     * sensorPortrait      - 按照物理传感器，只在纵向(2个方向)进行翻转(API >= 9)
     * userLandscape       - 按照用户选择，锁定一个横向，或者按照物理传感器进行横向的翻转(API >= 18)
     * userPortrait        - 按照用户选择，锁定一个纵向，或者按照物理传感器进行纵向的翻转(API >= 18)
     * fullUser    - 如果用户锁定了屏幕，它与"user"作用一致，如果是解锁了旋转，它与"fullSensor"作用一致(API >= 18)
     * locked      - 锁定了屏幕当前方向(API >= 18)
     *
     * @param activity
     * @param dir
     */
    public static void setScreenDirection(Activity activity, int dir) {
        activity.setRequestedOrientation(dir);
    }

}
